package com.example.codegen.service.impl;

import com.example.codegen.mapper.DatasourceMapper;
import com.example.codegen.model.Column;
import com.example.codegen.model.Datasource;
import com.example.codegen.model.Table;
import com.example.codegen.resolver.*;
import com.example.codegen.service.DatasourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DatasourceServiceImpl implements DatasourceService {

    private DatasourceMapper datasourceMapper;

    private MysqlResolver mysqlResolver;

    private PostgresResolver postgresResolver;

    private OracleResolver oracleResolver;

    private SqliteResolver sqliteResolver;

    @Autowired
    public DatasourceServiceImpl(DatasourceMapper datasourceMapper, MysqlResolver mysqlResolver, PostgresResolver postgresResolver, OracleResolver oracleResolver, SqliteResolver sqliteResolver) {
        this.datasourceMapper = datasourceMapper;
        this.mysqlResolver = mysqlResolver;
        this.postgresResolver = postgresResolver;
        this.oracleResolver = oracleResolver;
        this.sqliteResolver = sqliteResolver;
    }

    @Override
    public List<Datasource> getDatasourceList() {
        return datasourceMapper.getDatasourceList();
    }

    private BaseResolver getResolver(String databaseDriver) {
        BaseResolver resolver = null;
        switch (databaseDriver) {
            case "com.mysql.cj.jdbc.Driver":
            case "com.mysql.jdbc.Driver":
            case "org.gjt.mm.mysql.Driver":
                resolver = mysqlResolver;
                break;
            case "org.postgresql.Driver":
                resolver = postgresResolver;
                break;
            case "oracle.jdbc.driver.OracleDriver":
                resolver = oracleResolver;
                break;
            case "org.sqlite.JDBC":
                resolver = sqliteResolver;
                break;
            default:
                throw new RuntimeException("不支持的数据库类型");
        }
        return resolver;
    }

    @Override
    public String getVersion(Datasource datasource) {
        BaseResolver resolver = getResolver(datasource.getDatabaseDriver());
        return resolver.getVersion(datasource);
    }

    @Override
    public List<Table> getTables(Datasource datasource) {
        BaseResolver resolver = getResolver(datasource.getDatabaseDriver());
        return resolver.getTables(datasource);
    }

    @Override
    public Table getTable(Datasource datasource, String tableName) {
        BaseResolver resolver = getResolver(datasource.getDatabaseDriver());
        return resolver.getTable(datasource, tableName);
    }

    @Override
    public List<Column> getColumns(Datasource datasource, String tableName) {
        BaseResolver resolver = getResolver(datasource.getDatabaseDriver());
        return resolver.getColumns(datasource, tableName);
    }
}
